<template>
  <div class="login-container">
    <van-nav-bar
        title="登录后继续"
        left-arrow
        @click-left="goBack"
        border-bottom
    >
      <template #right>
        <van-button type="text" size="mini" @click="toggleLoginMode">
          {{ isVerificationLogin ? '切换密码登录' : '切换验证码登录' }}
        </van-button>
      </template>
    </van-nav-bar>

    <div class="logo-container">
      <img src="/logo.png" alt="积分换茶" class="logo" />
    </div>
    <div class="title">
      {{ isVerificationLogin ? '验证码一键登录' : '密码登录' }}
    </div>
    <div class="sub-title">
      {{ isVerificationLogin ? '新用户使用验证码一键登录将为您自动注册' : '使用密码登录享用所有服务' }}
    </div>

    <van-cell-group v-if="isVerificationLogin">
      <van-cell>
        <van-field
            v-model="phone"
            type="phone"
            placeholder="请输入手机号(新手机号自动注册)"
            :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误' }]"
        />
      </van-cell>

      <van-cell-group>
        <van-cell>
          <template #title>
            <van-field
                v-model="code"
                type="number"
                placeholder="请输入验证码"
                :rules="[{ required: true, message: '请填写验证码' }]"
                right-icon="loading"
            />
          </template>
          <template #right-icon>
            <van-button size="small" type="primary" @click="send" :disabled="!phoneValid || timeLeft > 0">
              {{ timeLeft > 0 ? `${timeLeft}s 后重新发送` : '发送验证码' }}
            </van-button>
          </template>
        </van-cell>
      </van-cell-group>
    </van-cell-group>

    <van-cell-group v-else>
      <van-cell>
        <van-field
            v-model="account"
            type="phone"
            placeholder="请输入用户名(或手机号)"
        />
      </van-cell>
      <van-cell>
        <van-field
            v-model="password"
            type="password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell>
    </van-cell-group>

    <van-checkbox-group v-model="agree">
      <van-checkbox name="agree">
        我已阅读并同意
        <van-link type="danger" href="">《用户协议》</van-link>
        和
        <van-link type="danger" href="">《隐私协议》</van-link>
      </van-checkbox>
    </van-checkbox-group>

    <van-button
        type="primary"
        block
        :loading="logging"
        @click="handleLogin"
        :disabled="(isVerificationLogin && (!code || agree.length === 0 || !phone )) || (!isVerificationLogin && (!password||!account||agree.length === 0))"
    >
      立即登录
    </van-button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import {useUserInfoStore} from '@/stores/userInfo.js'
import { useRouter } from 'vue-router';
import { ElMessage } from "element-plus";
import {sendCode} from "@/api/index.js";

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 响应式数据
const phone = ref('');
const code = ref('');
const password = ref('');
const logging = ref(false);
const agree = ref([]);
const isVerificationLogin = ref(true); // 控制当前登录方式，true为验证码登录，false为密码登录
const rightCode= ref('');
const timeLeft = ref(0); // 新增: 用于存储剩余时间
const account= ref('');
let timer = null; // 用于保存定时器ID

const phoneValid = computed(() => /^1[3456789]\d{9}$/.test(phone.value));

// 切换登录方式
const toggleLoginMode = () => {
  isVerificationLogin.value = !isVerificationLogin.value;
  if (!isVerificationLogin.value) {
    code.value = '';
    agree.value = [];
  } else {
    password.value = '';
  }
};

// 发送验证码
const send = async () => {
  if (timeLeft.value > 0) return; // 如果倒计时尚未结束，则不执行发送验证码操作

  try {
    let res;
    res = await sendCode(phone.value);
    console.log("验证码为"+res);
    rightCode.value = res;
    ElMessage.success({
      message: '验证码发送成功',
      duration: 2000,
    });

    // 开始倒计时
    timeLeft.value = 60;
    timer = setInterval(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    ElMessage.error({
      message: '验证码发送失败',
      duration: 2000,
    })
  }
};

// 处理登录
const handleLogin = async () => {
  logging.value = true;
  try {
    if (isVerificationLogin.value) {
      if (code.value !== rightCode.value) {
        ElMessage.error({
          message: '验证码错误',
          duration: 2000,
        })
        return;
      }
      await userInfoStore.codeLogin(phone.value);
    } else {
      await userInfoStore.pwdLogin( { account: account.value, password: password.value });
    }
    await router.push('/my')
  }catch (error){
    console.error('Error:', error.message);
  } finally {
    logging.value = false;
  }
};

// 返回上一页
const goBack = () => {
  window.history.back();
};

// 清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
.login-container {
  padding: 20px;
}
.logo-container {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}
.logo {
  width: 120px;
  height: 120px;
}
.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 16px;
}
.sub-title {
  text-align: center;
  color: #666;
  margin-bottom: 30px;
}
</style>
